package com.zjj.distributed.zk.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhanglei.zjj
 * @description Zookeeper官方客户端测试基类
 * @date 2023/6/18 17:01
 */
@Slf4j
public class StandaloneBase {
    private static final String CONNECT_STR = "192.168.200.129:2181";

    private static final int SESSION_TIMEOUT = 30 * 1000;

    protected static ZooKeeper zooKeeper = null;

    private static CountDownLatch initCtl = new CountDownLatch(1);

    // 异步操作流程控制
    protected static CountDownLatch processCtl = new CountDownLatch(1);

    private Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected
                    && event.getType() == Event.EventType.None) {
                initCtl.countDown();
                log.info("连接建立");
            }
        }
    };


    @Before
    public void init() {
        try {
            log.info(" start to connect to zookeeper server: {}", getConnectStr());
            // 有一个四个参数的重载方法，boolean类型，表示是否建立只读连接
            zooKeeper = new ZooKeeper(getConnectStr(), getSessionTimeout(), watcher);
            log.info(" 连接中...");
            initCtl.await();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static ZooKeeper getZooKeeper() {
        return zooKeeper;
    }


    @After
    public void test() {
        try {
            zooKeeper.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    protected String getConnectStr() {
        return CONNECT_STR;
    }

    protected int getSessionTimeout() {
        return SESSION_TIMEOUT;
    }
}
